package com.jnc.pay.biz.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.jnc.pay.biz.common.mapper.MchMapper;
import com.jnc.pay.biz.common.model.Mch;
import com.jnc.pay.biz.common.service.MchService;
import com.jnc.pay.constant.RedisConstant;
import com.jnc.pay.core.config.redis.RedisStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Auther: jjn
 * @Date: 2020/7/24
 * @Desc:
 */
@Slf4j
@Service
public class MchServiceImpl implements MchService {

    @Resource
    private MchMapper mchMapper;
    @Autowired
    private RedisStore redisStore;

    /**
     * 加载redis mch数据
     */
    @Override
    public void loadRedisMch() {
        List<Mch> list = mchMapper.queryMch();
        if(list == null || list.size() < 1){
            log.warn("No valid mch list ...");
            return;
        }
        for (Mch obj : list){
            Map<String, Object> map = BeanUtil.beanToMap(obj);
            //先清空老的缓存数据
            redisStore.del(RedisConstant.VALID_MCH_LIST + obj.getMchId());
            //再存入新的缓存数据
            redisStore.putHashValues(RedisConstant.VALID_MCH_LIST + obj.getMchId(), map);
        }
    }

    /**
     * 根据商户ID，获取商户信息(先从redis取，redis取不到再到数据库取)
     * @param mchId
     * @return
     */
    @Override
    public Mch getMchBy(Long mchId) {
        String key = RedisConstant.VALID_MCH_LIST + mchId;
        Map<String, Object> map = redisStore.getHashValue(key);
        //redis获取不到，从数据库里取，并写入redis
        if(MapUtil.isEmpty(map)){
            Mch mch = mchMapper.queryMchById(mchId);
            if(mch != null){
                Map<String, Object> dbMap = BeanUtil.beanToMap(mch);
                redisStore.putHashValues(key, dbMap);
            }
            return mch;
        }
        return BeanUtil.mapToBean(map, Mch.class, true);
    }
}
